package com.xindaoapp.happypet.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.MyMessageActivity;
import com.xindaoapp.happypet.activity.SettingActivity;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.MessageCenterInfo;
import com.xindaoapp.happypet.fragments.LoginFragment;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 登陆个人中心
 * 
 * @author chenghao
 * 
 */
public class PersonalCenterFragment_login extends BaseFragment implements OnClickListener {
    /** 登录按钮 */
    private View vLogin;
    /** 用户名 */
    private TextView vUserName;
    /** 用户头像 */
    private ImageView vUserIcon;

    private LoginSuccessReceiver mLoginSuccessReceiver;

    /** 登陆、已登陆显示页面 */
    private RelativeLayout lay_login, lay_logined;
    private Button bt_login;
    private PullToRefreshListView vPullToRefreshListView;


    private View vHeadView, vNoData;
    private TextView tv_name;
    private ImageView iv_touxiang, iv_setting, iv_tishi, iv_xiaoxi;
    private Button bt_qiandao;

    private ReceiveJpush mReceiveJpush;

    private MyAdapter mAdapter;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mLoginSuccessReceiver = new LoginSuccessReceiver();
        getActivity().registerReceiver(mLoginSuccessReceiver,
                new IntentFilter(Constants.ACTION_LOGIN_STATE_CHANGED));
        setUserInfos();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mLoginSuccessReceiver);
        getActivity().unregisterReceiver(mReceiveJpush);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        // initTopBg(view);

        lay_login = (RelativeLayout) view.findViewById(R.id.lay_login);
        lay_logined = (RelativeLayout) view.findViewById(R.id.lay_logined);
        bt_login = (Button) view.findViewById(R.id.bt_login);

        vPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview_user);
        // listView 中的第一项
        vHeadView = View.inflate(mActivity, R.layout.itemhead_fragment_user, null);
        tv_name = (TextView) vHeadView.findViewById(R.id.tv_name);
        iv_touxiang = (ImageView) vHeadView.findViewById(R.id.iv_touxiang);
        bt_qiandao = (Button) vHeadView.findViewById(R.id.bt_qiandao);
        iv_setting = (ImageView) vHeadView.findViewById(R.id.iv_setting);
        iv_tishi = (ImageView) vHeadView.findViewById(R.id.iv_tishi);
        iv_xiaoxi = (ImageView) vHeadView.findViewById(R.id.iv_xiaoxi);


        vNoData = view.findViewById(R.id.no_data);
        vPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        vPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);
        vPullToRefreshListView.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        vPullToRefreshListView.getRefreshableView().setOnItemLongClickListener(
                mOnItemLongClickListener);
        mReceiveJpush = new ReceiveJpush();
        getActivity().registerReceiver(mReceiveJpush,
                new IntentFilter(Constants.ACTION_RECEIVED_NOTICE));



    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);

        lay_login.setOnClickListener(this);
        lay_logined.setOnClickListener(this);
        bt_login.setOnClickListener(this);

        iv_touxiang.setOnClickListener(this);
        bt_qiandao.setOnClickListener(this);
        iv_setting.setOnClickListener(this);
        iv_tishi.setOnClickListener(this);
        iv_xiaoxi.setOnClickListener(this);



        vPullToRefreshListView.setOnScrollListener(new OnScrollListener() {

            private boolean isLoad;

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {

                if (isLoad) {

                }

            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                // TODO Auto-generated method stub
                if (arg1 == OnScrollListener.SCROLL_STATE_IDLE) {
                    isLoad = true;
                }

            }



        });

    }



    /**
     * 
     */
    private void initTopBg(View view) {
        LayoutParams params =
                new LayoutParams(CommonParameter.sScreenWidth,
                        CommonParameter.sScreenWidth * 327 / 640);
        view.findViewById(R.id.r_top).setLayoutParams(params);
    }

    private void setUserInfos() {
        if (UserState.isLogged()) {
            lay_login.setVisibility(View.GONE);
            lay_logined.setVisibility(View.VISIBLE);
            tv_name.setText("ok");
            // vUserName.setVisibility(View.VISIBLE);
            // vUserIcon.setVisibility(View.VISIBLE);
            // vUserName.setText(UserState.getUser().username);
            // ImageLoader.getInstance().displayImage(UserState.getUser().userface, vUserIcon);
        } else {
            lay_login.setVisibility(View.VISIBLE);
            lay_logined.setVisibility(View.GONE);
            // vUserName.setVisibility(View.GONE);
            // vUserIcon.setVisibility(View.GONE);
        }
    }

    @Override
    protected boolean showBottomTabBar() {
        return false;
    }

    @Override
    protected boolean showTopTabBar() {
        return false;
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.lay_login:
            case R.id.bt_login:

                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            LoginFragment.class.getCanonicalName());
                    startActivity(intent);
                }
                break;

            case R.id.iv_touxiang:
                intent.setClass(getActivity(), PersonCenterActivity.class);
                startActivity(intent);

                break;

            case R.id.iv_setting:

                intent.setClass(getActivity(), SettingActivity.class);
                startActivity(intent);

                break;
            case R.id.iv_xiaoxi:

                if (UserState.isLogged(getActivity())) {
                    intent.setClass(getActivity(), MyMessageActivity.class);
                    startActivity(intent);
                }

                break;

            default:
                break;
        }



    }


    //

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // MessageCenterInfo info = (MessageCenterInfo) parent.getAdapter().getItem(position);
            // handleOnClick(info, ((ViewHolder) view.getTag()).isNew);
        }
    };

    private void handleOnClick(MessageCenterInfo info, View isNew) {
        /*
         * if (info.type.equals(MESSAGETYPE .APP_PM.type)) { Intent i = new Intent(getActivity(),
         * PrivateLetterActivity.class); i .putExtra(Constants.KEY_TOUID , info.authorid);
         * i.putExtra(Constants .KEY_USERNAME, info.author); i.setFlags(Intent.
         * FLAG_ACTIVITY_NEW_TASK); getActivity ().startActivity(i); } else if
         * (info.type.equals(MESSAGETYPE .POST.type)) { Intent i = new Intent(getActivity(),
         * PostDetailActivity.class); i.putExtra("postID", info.tid); i.putExtra("pageNum",
         * info.curpage); i.putExtra("floor", info.curposition); i.setFlags(
         * Intent.FLAG_ACTIVITY_NEW_TASK ); getActivity().startActivity (i); } else if
         * (info.type.equals (MESSAGETYPE.SYSTEM.type)) { Intent intent = new Intent(getActivity(),
         * MainActivity.class); intent.putExtra (Constants.KEY_SKIP_CLASS_NAME ,
         * SystemInformFragment.class. getCanonicalName()); Bundle bundle = new Bundle(); intent.
         * putExtra(Constants.KEY_BUNDLE , bundle); getActivity().startActivity (intent); } if
         * (info.isnew == 1) { info.isnew = 0; isNew.setVisibility (View.GONE); HappyPetApplication
         * .get().getMoccaApi ().noticeClick(info.id, new IRequest<Boolean>() {
         * 
         * @Override public void request(Boolean t) { if (t) { Constants
         * .NoticeLabel.sHasNewMessageNotice = true; } else { Constants.NoticeLabel
         * .sHasNewMessageNotice = false; } Intent notice = new Intent(Constants.
         * KEY_NOTICE_STATE_CHANGED); getActivity ().sendBroadcast(notice); } }); }
         */}

    private final OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            // delete(((MessageCenterInfo) parent.getAdapter().getItem(position)));
            return false;
        }
    };


    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    onLoadData();

                }
            };

    @Override
    protected void onLoadData() {
        super.onLoadData();



        if (CommonUtil.checkNetState(mActivity)) {
            getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
                @Override
                public void request(HomeBannerEntity t) {
                    vPullToRefreshListView.onRefreshComplete();
                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    } else {
                        mAdapter = new MyAdapter();
                        vPullToRefreshListView.setAdapter(mAdapter);
                    }
                }
            });
        } else {
            Toast.makeText(mActivity, "当前无网络，请检查网络！", 1).show();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    vPullToRefreshListView.onRefreshComplete();
                }
            }).start();
        }



    }

    //


    class LoginSuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            setUserInfos();
        }

    }

    class ReceiveJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            onLoadData();
        }

    }


    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 5;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int pos, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub

            ViewHolder holder;
            if (pos == 0) {
                // 设置头部

                return vHeadView;
            } else if (arg1 == null) {
                holder = new ViewHolder();
                arg1 = View.inflate(mActivity, R.layout.item_person_center, null);
                arg1.setTag(holder);
            } else {
                holder = (ViewHolder) arg1.getTag();
            }

            // 设置推荐内容

            return arg1;

        }

        class ViewHolder {

            TextView tv_title, tv_time, tv_source;
            ImageView iv_img;

        }

    }

}
